<template>
  <base-breadcrumb v-loading="loading" :isAudit="isAudit">
    <div class="about-master-container">
      <a-card>
        <title-name title="基本信息"></title-name>
        <BForm
          ref="BForm"
          :config="formConfig"
          :form="form"
          :rule="rules"
        />
      </a-card>

      <div class="tar page-btn-right-top">
        <BasePrintButton
          v-if="form.id && disabled && !this.$route.query.businessId"
          :before-print-fn="beforePrintFn"
          style="display: inline-block;margin-right: 20px;"
        />
        <template v-if="!disabled">
          <a-button type="primary" @click="save(form.auditStatus)" class="mr20">保存</a-button>
          <a-button v-if="form.auditStatus !== 'PAST'" type="primary" @click="submit('SUBMITTED')" class="mr20">提交
          </a-button>
        </template>
        <a-button v-checkVisibleInDetail @click="$close">关闭</a-button>
      </div>
    </div>
    <SelectPerson
      title="选择人员"
      primaryKey="userId"
      :org-id="form.signOrgId"
      :list.sync="form.penaltyUser"
      :visible.sync="selectPersonVisible2"
    >
    </SelectPerson>

    <addCheckRecordModal
      :outSelectRows="form.checkList"
      :isPerson="form.penaltyType === 2"
      :out-params="outParams"
      :visible.sync="visible"
      @ok="addCheckRecord"
    />
  <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import SelectTreeCommon from '@/components/Select/SelectTreeCommon'
import addCheckRecordModal from './addCheckRecordModal'
import { queryProjectTree } from '@/api/subassembly/TreeSelectOrganization'
import BSelect from '@/components/BComponents/BSelect'
import { getSubcontractor } from '@/api/businessAffairs/sml'
import BUploadVModel from '@/components/BComponents/BUploadVModel'
import Api from '@/api/safetySupervision/safeProductAwardPunish/fineForBreachOfContract'
import SelectPerson from '@/components/Select/SelectPerson'

export default {
  name: 'edit',
  components: { addCheckRecordModal, SelectPerson },
  computed: {
    formConfig() {
      return [
        {
          row: true,
          children: [
            {
              type: 'radio', value: 'penaltyType', label: '罚款类型',
              colSpan: 24,
              attrs: {
                horizontal: true,
                disabled: this.disabled,
                data: [
                  { id: 0, name: '内部单位', disabled: this.$currentPost().code === 'PD' },
                  { id: 1, name: '外部单位', disabled: this.$currentPost().code !== 'PD' },
                  { id: 2, name: '个人' }
                ]
              },
              on: {
                change: e => {
                  this.form.penaltyOrgId = ''
                  this.form.penaltyOrgName = ''
                  this.form.penaltyOrgTag = ''
                  // this.form.penaltyUser = []
                  this.form.penaltyType = e.target.value
                  this.setOutParams()
                }
              }
            },
            { type: 'input', value: 'signOrgName', label: '签发单位', attrs: { disabled: true } },
            {
              type: SelectTreeCommon,
              value: 'penaltyOrgId',
              label: '被处罚单位',
              show: this.form.penaltyType === 0,
              attrs: {
                disabled: this.disabled,
                key: 1,
                returnFindItem: true,
                replaceFields: { children: 'childTree', title: 'orgName', key: 'orgId', value: 'orgId' },
                needLink: false,
                api: async () => {
                  let res = await queryProjectTree()
                  if (res.code === 200 && res.data) {
                    return { code: this.SUCCESS_CODE, data: res.data.childTree }
                  }
                  return { code: this.SUCCESS_CODE, data: [] }
                }
              },
              on: {
                selectChange: e => {
                  this.form.penaltyOrgId = e.orgId
                  this.form.penaltyOrgName = e.orgName
                  this.form.penaltyOrgTag = e.tageCode
                  this.form.projectId = e.projectId
                  this.form.branchComId = e.parentId
                  this.setOutParams()
                },
                selectParentChange: e => {
                  console.log(e)
                }
              }
            },
            {
              type: BSelect,
              value: 'penaltyOrgId',
              label: '被处罚单位',
              show: this.form.penaltyType === 1,
              attrs: {
                disabled: this.disabled,
                keys: ['subContractorId', 'name'],
                request: () => getSubcontractor({ pageSize: 1000, pageNo: 1, id: this.form.projectId })
              },
              on: {
                selectChange: e => {
                  this.form.penaltyOrgId = e.subContractorId
                  this.form.penaltyOrgName = e.name
                  this.setOutParams()
                }
              }
            },
            {
              type: 'custom',
              value: 'penaltyUser',
              label: '被处罚对象',
              noFixed: true,
              show: this.form.penaltyType === 2,
              render: () => {
                return (
                  <div key="2">
                    {this.form.penaltyUser.map(v => {
                      return (
                        <a-tag className="mb10p" key={v.id}>
                          {v.name}
                        </a-tag>
                      )
                    })}
                    {
                      (!this.disabled) && <a-tag style="background: #fff; borderStyle: dashed;"
                                                 onClick={() => this.selectPersonVisible2 = true}
                      >
                        <a-icon type="plus" />
                        选择人员
                      </a-tag>
                    }
                  </div>
                )
              }
            },
            {
              type: 'date-picker', value: 'penaltyDate', label: '处罚时间', attrs: {
                disabled: this.disabled,
                valueFormat: 'YYYY-MM-DD'
              }
            },
            {
              type: 'custom',
              value: 'content',
              label: '罚款事由',
              colSpan: 24,
              noFixed: true,
              render: () => {
                return (
                  <div>
                    {
                      (!this.disabled) && <a-button class="mb20" onClick={e => this.showDialog()}>选择</a-button>
                    }
                    {
                      this.form.checkList.length !== 0 &&
                      <a-table
                        pagination={false}
                        columns={this.columns}
                        data-source={this.form.checkList}
                      />
                    }
                    <BaseTextarea disabled={this.disabled} v-model={this.form.content} class="mt20 requiredFormItem" />
                  </div>
                )
              }
            },
            {
              type: 'number', value: 'penaltyAmount', label: '罚款金额(元)',
              attrs: { disabled: this.disabled, min: 0, precision: 2 }
            },
            { type: 'input', value: 'creatorName', label: '填报人', attrs: { disabled: true } },
            { type: 'input', value: 'submitDate', label: '填报时间', attrs: { disabled: true } },
            {
              type: BUploadVModel, value: 'fileInfoList', label: '照片上传', noFixed: true,
              attrs: { disabled: this.disabled, businessCode: 'SHE13', uploadType: 'image-list' }
            }
          ]
        }
      ]
    }
  },
  props: {
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.disabled = true
        }
      }
    }
  },
  data() {
    return {
      beforePrintFn: async () => {
        let res = await Api.print({}, { id: this.form.id })
        return res.data.content
      },
      loading: false,
      visible: false,
      selectPersonVisible2: false,
      form: {
        id: null,
        auditStatus: 'DRAFT',
        penaltyType: null,
        signOrgId: '',
        penaltyOrgId: '',
        penaltyOrgTag: '',
        projectId: this.$currentPost().projectId,
        creatorName: this.$userInfo().name,
        submitDate: this.$dateFormat(Date.now(), 'D'),
        signOrgName: '',
        signOrgTag: '',
        checkList: [],
        fileInfoList: [],
        penaltyUser: []
      },
      outParams: {},
      columns: [
        { title: '检查区域', dataIndex: 'respAreaStr', width: 250 },
        { title: '问题', dataIndex: 'securityControlEnumStr', width: 100 },
        { title: '检查时间', dataIndex: 'createTime', width: 200 },
        {
          title: '整改状态', dataIndex: 'safetyAuditStatusEnumStr', width: 100, customRender: (text, row, index) => {
            if (row.safetyAuditStatusEnumStr === '待整改' && row.isBeyond == '1') {
              return '超期未整改'
            }
            return row.safetyAuditStatusEnumStr
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 120,
          fixed: 'right',
          customRender: (text, row, index) => {
            return (
              <div class="pub-table-list-action">
                {
                  (!this.disabled) && <span onClick={e => this.delCheckRecord(index)}>删除</span>
                }
              </div>
            )
          }
        }
      ],
      rules: {
        penaltyAmount: [{ required: true, message: '请填写罚款金额(元)', trigger: 'blur' }],
        // content: [{ required: true, message: '请填写罚款事由', trigger: 'blur' }],
        penaltyOrgId: [{ required: true, message: '请选择被处罚单位', trigger: 'change' }],
        penaltyType: [{ required: true, message: '请选择罚款类型', trigger: 'change' }],
        penaltyUser: [{ type: 'array', required: true, message: '请选择被处罚对象', trigger: 'change' }],
        fileInfoList: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }],
        penaltyDate: [{ required: true, message: '请选择处罚时间', trigger: 'change' }]
      },
      disabled: this.$route.query.pageType === 'look',
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  created: async function() {
    if (this.$currentPost().code === 'PD') {
      this.form.signOrgTag = 'PD'
      this.form.signOrgId = this.$currentPost().id
      this.form.signOrgName = this.$currentPost().name
      this.form.postName = this.$currentPost().postCode
    }
    if (this.$currentPost().code === 'BC' || this.$currentPost().code === 'CO') {
      this.form.postName = this.form.signOrgTag = this.$currentPost().code
      this.form.signOrgId = this.$currentPost().orgId
      this.form.signOrgName = this.$currentPost().code === 'BC' ? this.$currentPost().orgName : '西南公司安全生产委员会'
    }
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      await this.getData()
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('penalty_rate_account')
  },
  methods: {
    showDialog() {
      if (this.form.penaltyType === null) return this.$noticeWarning('请选择罚款类型')
      if (this.form.penaltyType === 1 && !this.form.penaltyOrgId) return this.$noticeWarning('请选择被处罚单位')
      if (this.form.penaltyType === 0 && !this.form.penaltyOrgId) return this.$noticeWarning('请选择被处罚单位')
      this.visible = true
    },
    setOutParams(isResetList = true) {
      if (isResetList) {
        this.form.checkList = []
      }
      if (this.form.penaltyType === 2) return this.outParams = {}
      if (this.form.penaltyType === 1) return this.outParams = { subcontractorId: this.form.penaltyOrgId }
      if (this.form.penaltyType === 0) {
        if (this.form.penaltyOrgTag === 'BC') return this.outParams = { branchComId: this.form.penaltyOrgId }
        if (this.form.penaltyOrgTag === 'PD') return this.outParams = {
          branchComId: this.form.branchComId,
          projectId: this.form.projectId
        }
      }
    },
    delCheckRecord(index) {
      this.$submitConfirm(() => {
        this.form.checkList.splice(index, 1)
      }, '确定删除数据？')
    },
    addCheckRecord(e) {
      this.form.checkList = this.form.checkList.concat(e)
    },
    async getData() {
      this.loading = true
      let res = await Api.findListByMainId({}, { id: this.form.id })
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.form = this.$clone(res.data)
        this.setOutParams(false)
        if (!this.form.fileInfoList) this.form.fileInfoList = []
        if (res.data.penaltyUser) {
          this.form.penaltyUser = []
          for (const key in res.data.penaltyUser) {
            this.form.penaltyUser.push({ id: Date.now(), userId: key, name: res.data.penaltyUser[key] })
          }
        }
      }
    },
    async checkValidate() {
      if (this.form.checkList.length === 0 && (!this.form.content)) {
        this.$noticeWarning('罚款事由二选一必填')
        return false
      }
      return new Promise(resolve => {
        this.$refs.BForm.validate((valid) => {
          resolve(valid)
        })
      })
    },
    async submit(status) {
      if (await this.checkValidate()) {
        await this.save(status)
      }
    },
    async save(status) {
      this.setProcessConfig = null;  
      let temp = this.$clone(this.form)
      temp.auditStatus = status
      if (temp.penaltyUser) {
        let temp2 = {}
        temp.penaltyUser.map(v => temp2[v.userId] = v.name)
        temp.penaltyUser = temp2
      }

      this.loading = true
      let res
      this.submitApprovalConfirm(status =='SUBMITTED' ? this.processConfig : 6, async (flag)=>{
        if(!flag) {
          this.loading = false
          return
        }
        if (temp.id) {
          res = await Api.editByMain(temp)
        } else {
          res = await Api.createByMain(temp)
        }
        this.loading = false
        if (res.code === this.SUCCESS_CODE) {
          this.$noticeSuccess('操作成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
            this.businessId = res.data.id;
            this.setProcessConfig = this.processConfig;
            return
          }else{
            this.$close()
          }
        }
      })

    }
  }
}
</script>